const {BlogType} = require("../model");

const ROUTERURL = require("../routerConfig");
const {setR,delR,getR,caseTime} = require('./redisServe')
exports.addType = async (typeString)=>{
    if(!typeString) return "typeString is null";
    const is = await BlogType.find({name:typeString})
    if(is.length > 0) return '该分类已存在，不能重复添加'
    const result = await BlogType.create({
        name:typeString
    })
    delR(0,ROUTERURL.getType);
    return result
}

exports.upType = async (_id,typeString,sum)=>{
    if(!typeString) return "typeString is null";
    const result = await BlogType.updateOne(
        {
            _id
        },{
            $set:{
                name:typeString,
                sum
            }
           
        }
    )
    delR(0,ROUTERURL.getType);
    return result;
}
exports.upTypesum = async (name,i=+1)=>{ 
    if((i == +1 || i == -1) && name){
      const result =   await BlogType.updateOne({
         name
        },{
            $inc:{
                sum:i
            }
        });
        delR(0,ROUTERURL.getType);
        return result;
    }
    return "_Id不正确或不规范,第二参数加法为+1，减法为-1";

}
exports.delType = async (_id)=>{
    if(!_id) return "Id is null";
    const result =  BlogType.deleteOne({_id});

    delR(0,ROUTERURL.getType);

    return result;
}

exports.getBlogType = async ()=>{
    
   const CRouter = await getR(0,ROUTERURL.getType);
   if(CRouter) return  JSON.parse(CRouter);
    const result = await BlogType.find();
    setR(0,ROUTERURL.getType,JSON.stringify(result),{EX:caseTime});

    return result;
}
